package com.x.compute.core.handle;

import com.x.compute.core.context.VariableContext;
import com.x.compute.core.handle.column.ColumnVarHandle;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 列变量处理工厂
 * @author xuxin
 */
@Component
@DependsOn(value = "variableContext")
public class ColumnVarHandleFactory implements InitializingBean, ApplicationContextAware {

    private static Map<String, ColumnVarHandle> HANDLE_MAP = new ConcurrentHashMap<>();

    private ApplicationContext applicationContext;

    /**
     * 获取处理器
     * @param tableId 表格id
     * @return
     */
    public static ColumnVarHandle getHandle(String tableId){
        Assert.state(HANDLE_MAP.containsKey(tableId),"Illegal tableId key");
        return HANDLE_MAP.get(tableId);
    }

    @Override
    public void afterPropertiesSet(){
        applicationContext.getBeansOfType(ColumnVarHandle.class).values().forEach(handler -> HANDLE_MAP.put(handler.getTableId(), handler));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
